using System;
using Shinkansen.Core;
using Shinkansen.Support;

namespace Shinkansen.Model
{
    public class CrunchedStaticResource : IStaticResource
    {
        private readonly IStaticResource _resource;
        private readonly IJsCruncher _jsCruncher;
        private readonly ICssCruncher _cssCruncher;
        private readonly ResourceInformation _ri;

        /// <summary>
        /// Initializes a new instance of the <see cref="CrunchedStaticResource"/> class.
        /// </summary>
        /// <param name="resource">The resource.</param>
        /// <param name="jsCruncher">The JavaScript crucher.</param>
        /// <param name="cssCruncher">The CSS crucher.</param>
        /// <param name="ri">The ri.</param>
        public CrunchedStaticResource (IStaticResource resource, IJsCruncher jsCruncher, ICssCruncher cssCruncher, ResourceInformation ri)
        {
            _resource = resource;
            _jsCruncher = jsCruncher;
            _cssCruncher = cssCruncher;
            _ri = ri;
        }

        /// <summary>
        /// Crunches content of the static resource.
        /// </summary>
        /// <returns></returns>
        public byte[] GetContent ()
        {
            byte[] content = _resource.GetContent ();

            if (!_ri.Crunch)
                return content;
            
            byte[] crunchedContent;
            switch (_ri.ResourceType)
            {
                case ResourceType.JavaScript:
                    crunchedContent = _jsCruncher.Process (content);
                    break;

                case ResourceType.Css:
                    crunchedContent = _cssCruncher.Process (content);
                    break;

                default:
                    throw new InvalidOperationException (
                        string.Format ("Minification for resource type '{0}' is not supported.", _ri.ResourceType));
            }

            return crunchedContent;
        }
    }
}